<template>
  <div class="profile-content-item profile-update-password">
    <DFForm
      class="basicForm"
      getLabelFrom="table"
      labelPlacement="left"
      require-mark-placement="left"
      :labelWidth="140"
      @register="passwordFormRegister"
      @submit="handleSavePasswordFn"
    />
    <n-button class="save-button" type="primary" :loading="loading" @click="handleSavePasswordFn">
      {{ t('common.button.save') }}
    </n-button>
  </div>
</template>

<script lang="ts" setup name="Profile">
  import { ref, Ref } from 'vue';
import {
  useRouter,
  // useRoute
} from 'vue-router';
  import { useUserStore } from '@/store/modules/user';
  import { DFForm, FormSchema, useForm } from '@/components/DFForm/index';
  import { FormItemRule, useMessage } from 'naive-ui';
  import { useMixins } from '@/hooks/useMixins';
  import { checkPassWordFn } from '@/utils/formCheck';
  import { accountPassword } from '@/api/system/user';
  // import { encrypt } from '@/utils/jsencrypt';
  import lang from '../lang';
  import { t } from '@/i18n';

  const { loadLangFn } = useMixins();
  loadLangFn(lang);

  const message = useMessage();
  const router = useRouter();
  // const route = useRoute();
  const userStore = useUserStore();

  const loading = ref(false);

  // 修改密码表单
  const passwordFormSchemas: FormSchema[] = [
    {
      field: 'oldPassword',
      component: 'NInput',
      label: 'oldPassword',
      componentProps: {
        type: 'password',
        'show-password-on': 'click',
        maxlength: 20,
        minlength: 6,
        placeholder: t('profile.form.plsInputPwd'),
      },
      rules: [
        {
          required: true,
          message: t('common.formTipMsg.input'),
          trigger: 'input',
        },
      ],
    },
    {
      field: 'newPassword',
      component: 'NInput',
      label: 'newPassword',
      componentProps: {
        type: 'password',
        'show-password-on': 'click',
        maxlength: 20,
        minlength: 6,
        placeholder: t('profile.form.plsInputPwd1'),
      },
      rules: [
        {
          required: true,
          message: t('common.formTipMsg.input'),
          trigger: 'input',
        },
        {
          validator(_rule: FormItemRule, value: string) {
            const passwordData = getPasswordFormValFn();
            const { oldPassword } = passwordData || {};
            if (value && oldPassword === value) {
              return new Error(t('common.formTipMsg.pwdEqualOldError'));
            }
            return checkPassWordFn(value, false);
          },
          trigger: 'blur',
        },
      ],
    },
    {
      field: 'confirmNewPassword',
      component: 'NInput',
      label: 'confirmNewPassword',
      componentProps: {
        type: 'password',
        'show-password-on': 'click',
        maxlength: 20,
        minlength: 6,
        placeholder: t('profile.form.plsInputPwd2'),
      },
      rules: [
        {
          required: true,
          message: t('common.formTipMsg.input'),
          trigger: 'input',
        },
        {
          validator(_rule: FormItemRule, value: string) {
            const passwordData = getPasswordFormValFn();
            const { newPassword } = passwordData || {};
            if (value && newPassword !== value) {
              return new Error(t('common.formTipMsg.passwordErr'));
            }
            return checkPassWordFn(value, false);
          },
          trigger: 'blur',
        },
      ],
    },
  ];
  const [
    passwordFormRegister,
    {
      validate: passwordValidate,
      getFieldsValue: getPasswordFormValFn,
      // setFieldsValue: setPasswordFormValFn,
    },
  ] = useForm({
    gridProps: { cols: 1 },
    collapsedRows: 3,
    labelWidth: 140,
    layout: 'horizontal',
    showActionButtonGroup: false,
    schemas: passwordFormSchemas,
  });
  type Props = {
    userName: string | null;
  };
  const props = withDefaults(defineProps<Props>(), {
    userName: '',
  });
  const userName: Ref<string | null> = ref('');
  watch(
    () => props.userName,
    (newVal: string | null) => {
      userName.value = newVal;
    },
    { immediate: true, deep: true }
  );

  const $dialog = window['$dialog'];
  // 保存密码
  const handleSavePasswordFn = async () => {
    loading.value = true;
    try {
      const isSubmit = await passwordValidate();
      if (!isSubmit) {
        const passwordForm = getPasswordFormValFn();
        const { oldPassword, newPassword } = passwordForm || {};
        const res = await accountPassword({
          // userName: userName.value,
          oldPassword,
          newPassword,
        });
        if (res.code === 200) {
          // const userStore = useUserStoreWidthOut();
          message.success(t('common.tipMsg.saveSuccess'));
          // const { nickName, userName, phoneCode, remark } = row || {};
          // userInfo = { nickName, userName, phoneCode, remark };
          // await userStore.getInfo();
          loading.value = false;
          // buttonDisabled.value = true;

          $dialog.warning({
            title: t('common.tipMsg.warning'),
            content: t('common.tipMsg.logoutConfirmMsg2'),
            positiveText: t('common.button.primary'),
            //negativeText: '取消',
            closable: false,
            maskClosable: false,
            onPositiveClick: () => {
              userStore.logout().then(() => {
                router
                  .replace({
                    name: 'Login',
                  })
                  .finally(() => location.reload());
              });
            },
            onNegativeClick: () => {},
          });
          // logOut();
        }
      }
    } catch (e) {
      console.log(e);
      loading.value = false;
    }
  };

  // const logOut = () => {
  //   userStore.logout().then((res: any) => {
  //     const { message: msg = '', code } = res;
  //     if (code !== 0) {
  //       msg && message.success(msg);
  //     }

  //     router
  //       .replace({
  //         name: 'Login',
  //         query: {
  //           redirect: route.fullPath,
  //         },
  //       })
  //       .finally(() => window.location.reload());
  //   });
  // };
</script>

<style lang="less" scoped>
  .profile {
    &-content {
      &-item {
        width: 500px;
        margin: 0 auto;
        .basicForm {
          margin-bottom: 12px;
          // margin-left: -84px;
          // padding-right: 56px;
        }
      }
      .save-button {
        margin-left: 142px;
        padding: 0 22px;
        height: 32px;
        line-height: 32px;
      }
    }
  }
</style>
